# -*- coding: utf-8 -*-
#用户提现
import base
import json,uuid,time,traceback,os
import requests,datetime
import pika,logging,sys
from Message.models import *
from Message.tool_wechat import *
from main.settings import REDIS_STORE_URL,RABBITMQ_HOST_URL,RABBITMQ_USER,RABBITMQ_USER_PASSWORD,RABBITMQ_PORT
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class MqConsumer(object):
    """
    构造请求数据
    """
    def __init__(self):
        self.user=RABBITMQ_USER
        self.pwd=RABBITMQ_USER_PASSWORD
        self.host=RABBITMQ_HOST_URL
        self.port=RABBITMQ_PORT
        self.virtual_host='/'
        self.exchange = 'pay-topic'
        self.routing_key = '*.pay'
        self.queue='user-pay'
    
    #接收消息
    def action(self):
        try:
            # self.linshi_que()
            self.durable_que_topic()
            
        except:
            traceback.print_exc()

    def durable_que_topic(self):
        credentials = pika.PlainCredentials(self.user, self.pwd)  # mq用户名和密码
        # 虚拟队列需要指定参数 virtual_host，如果是默认的可以不填。
        connection = pika.BlockingConnection(pika.ConnectionParameters(host = self.host,port = self.port,virtual_host = self.virtual_host,credentials = credentials))
        channel=connection.channel()

        print('self.routing_key----',self.routing_key)

        # 声明exchange，由exchange指定消息在哪个队列传递，如不存在，则创建。durable = True 代表exchange持久化存储，False 非持久化存储
        channel.exchange_declare(exchange = self.exchange,durable = True, exchange_type='topic')

        # 声明消息队列，消息将在这个队列传递，如不存在，则创建。durable = True 代表消息队列持久化存储，False 非持久化存储

        result = channel.queue_declare(queue = self.queue,durable = True)
        
        # 绑定exchange和队列  exchange 使我们能够确切地指定消息应该到哪个队列去
        channel.queue_bind(exchange = self.exchange,queue = self.queue,routing_key=self.routing_key)
        # 定义一个回调函数来处理消息队列中的消息，这里是打印出来
        def callback(ch, method, properties, body):
            ch.basic_ack(delivery_tag = method.delivery_tag)
            print(u'print-method--',method.delivery_tag,method.routing_key)
            print(u'print-body--',body)
            msgobj = body.decode()
            currrtkey = method.routing_key
            
            
            try:
                msgobj = json.loads(msgobj)
                print(u'projectjson--',msgobj,type(msgobj))

                logger.info('projectjson----------')
                logger.info(msgobj)
                app_id = 'wxff92ea6443261eee'
                if 'appid' in msgobj.keys():
                    app_id = msgobj['appid']
                if currrtkey=='user.pay':#提现罗辑
                    # app_id = 'wxff92ea6443261eee'
                    api_key = '1e62fba4dac15df3ffe12373a49a89dc'
                    mch_id = '1503959351'
                    mch_cert = CERT_DIR+'fuwuhao/apiclient_cert.pem'
                    mch_key = CERT_DIR+'fuwuhao/apiclient_key.pem'

                    wpa = WeChatPayApi(app_id,api_key,mch_id,mch_key,mch_cert)

                    user_id = msgobj['user_id']
                    amount = msgobj['amount']
                    desc = msgobj['desc']
                    client_ip = msgobj['client_ip']
                    check_name = msgobj['check_name']
                    real_name = None
                    out_trade_no = msgobj['out_trade_no']
                    device_info = msgobj['device_info']
                    operate_code = msgobj['operate_code']
                    uid = msgobj['uid']
                    redirect = msgobj['redirect']
                    
                    #企业转账
                    res = wpa.zhuanzhang(user_id, int(amount), desc, client_ip, check_name, real_name, None, device_info)

                    try:
                        # print("res----",json.dumps(res))
                        pydata = {'uid':uid,'amount':int(amount),'operate_code':operate_code,"out_trade_no":out_trade_no,"result":json.dumps(res)}
                        requests.get(redirect,params=pydata)
                    except Exception as e:
                        print('回调异常')
                        # traceback.print_exc()
            except Exception as e:
                print('数据解析异常')
                # traceback.print_exc()
                res = e
            
                try:
                    # print("res----",json.dumps(res))
                    uid = msgobj['uid']
                    amount = msgobj['amount']
                    pydata = {'uid':uid,'amount':int(amount),'operate_code':operate_code,"out_trade_no":out_trade_no,"result":json.dumps(res)}
                    requests.get(redirect,params=pydata)
                except Exception as e:
                    print('回调异常')
                
            
        # 告诉rabbitmq，用callback来接收消息
        channel.basic_consume(self.queue,callback)# 设置成 False，在调用callback函数时，未收到确认标识，消息会重回队列。True，无论调用callback成功与否，消息都被消费掉

        print(u'connecting---',self.queue)
        # 开始接收信息，并进入阻塞状态，队列里有信息才会调用callback进行处理
        channel.start_consuming()
if __name__ == "__main__":
    mqc = MqConsumer()
    mqc.action()
    # mqc.del_quene()



    

    
